import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../../dd_core/dd_config.dart';
import '../../../dd_core/dd_hive_dao.dart';
import '../../../dd_core/dd_http.dart';
import '../../../dd_core/dd_user_service.dart';
import '../../../dd_models/dd_hive_works_model.dart';
import '../../../dd_models/dd_oauth_model.dart';


class DDMyFollowController extends GetxController {

  final datas = <FollowUser>[].obs;

  @override
  onInit() {
    super.onInit();
    getList();
  }

  getList() async {

    EasyLoading.show();
    Map<String, dynamic>? result = await getFriendsListPage(40,0);
    EasyLoading.dismiss();
    if (result != null && result['code'] == 0) {
      List<Map<String, dynamic>> data = List<Map<String, dynamic>>.from(result['data']);
      datas.value = data.map((e) => FollowUser.fromJson(e)).toList();
    }

    // final prefs = await SharedPreferences.getInstance();
    // String cureenUid = await prefs.getString(DDKey.cureenUid) ?? "";
    // List<HiveWorksModel>? d = await DDHiveDao.getMyFollowList(uid: cureenUid);
    // if (d != null) {
    //   final Set<String> uniqueUserIds = {};
    //   final List<HiveWorksModel> uniqueList = d.where((item) {
    //     return uniqueUserIds.add(item.userId!);
    //   }).toList();
    //   datas.value = uniqueList;
    //   datas.refresh();
    // }
  }


  updateMyFollow(FollowUser m) async {

    EasyLoading.show();
    Map<String, dynamic>? result = await unfriend(m.userId ?? '');
    EasyLoading.dismiss();
    if (result != null && result['code'] == 0) {

      HiveWorksModel hiveWorksModel = HiveWorksModel();
      hiveWorksModel.userId = m.userId;

      await DDHiveDao.updateFencingFollow(hiveWorksModel:hiveWorksModel, myFollow: false);
      getList();
        EasyLoading.showToast("Unfollow successful",
            duration: Duration(seconds: 2));
    }
  }


  @override
  void onClose() {
    datas.close();
    super.onClose();
  }
}

class FollowUser {
  final String nickname;
  final String avatar;
  final String avatarUrl;
  final int age;
  final String country;
  final String userId;

  FollowUser({
    required this.nickname,
    required this.avatar,
    required this.age,
    required this.avatarUrl,
    required this.country,
    required this.userId,
  });

  factory FollowUser.fromJson(Map<String, dynamic> json) {
    return FollowUser(
      nickname: json['nickname'],
      avatar: json['avatar'],
      age: json['age'],
      country: json['country'],
      userId: json['userId'],
      avatarUrl: json['avatarUrl'],
    );
  }
}